package com.nikmesoft.android.alwaysontime.activities;


import java.util.Calendar;

import com.nikmesoft.android.alwaysontime.R;
import com.nikmesoft.android.alwaysontime.daos.TasksDAO;
import com.nikmesoft.android.alwaysontime.models.Task;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;




public class TasksActivityAdd extends BaseActivity  {
	Spinner spnPriorityAddTask, spnTypeAddTask, spnSoundAddTask;
	Button btnTimeAddTask,btnDateAddTask, btnOKAddTask, btnDelAddTask;
	EditText txtDateAddTask, txtTimeAddTask, txtContentAddTask;
	RatingBar rtbarAddTask;
	CheckBox chkStatusAddTask;
	int day, month, year, hour, minute, ampm;
	DatePicker datePicker;
	TimePicker timePicker;
	final int DIALOG_DATE = 1, DIALOG_TIME = 2;
	final Context context = this;
	private int selected_id;	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_tasks_add);
		View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.activity_tasks_add, null);
		this.setContentView(viewToLoad);
		init();
		// get info from intent
		getInfoFromIntent();
	}

	public void init(){
		selected_id=0;
		//txtContentAddTask
		txtContentAddTask = (EditText) findViewById(R.id.txtContentAddTask);
		
		//rating bar
		rtbarAddTask = (RatingBar) findViewById(R.id.rtbarAddTask);
		rtbarAddTask.setRating(1);
		
		//Checkbox
		chkStatusAddTask = (CheckBox) findViewById(R.id.chkStatusAddTask);
		chkStatusAddTask.setChecked(false);
		chkStatusAddTask.setText("not finish");
		addCheckBoxListener();
		
		getDataForSpinner();
		addSpinnerListener();
		// connect to change Button
		connectChangeButton();
		// xu ly button OK and DELETE
		btnOKAddTask = (Button) findViewById(R.id.btnOKAddTask);
		btnDelAddTask = (Button) findViewById(R.id.btnDelAddTask);
		AddListenerForOKDELETEButton();
	}


	//-----------checkbox listener ------------
	public void addCheckBoxListener() {
		chkStatusAddTask.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
			    if (isChecked) {
			    	chkStatusAddTask.setText("finish");
			      }
			      else {
			    	chkStatusAddTask.setText("not finish");
			      }
			}
		});

	}
		
	//--------- get data spinner--------
	public void getDataForSpinner()
	{	// connect spinner
		spnPriorityAddTask = (Spinner) findViewById( R.id.spnPriorityAddTask);
		spnTypeAddTask = (Spinner) findViewById(R.id.spnTypeAddTask);
		spnSoundAddTask = (Spinner) findViewById( R.id.spnSoundAddTask);
		//setdefault checked for spinner
		spnPriorityAddTask.setSelection(0);//normal
		spnTypeAddTask.setSelection(0);//private
		spnSoundAddTask.setSelection(0);//Ring Ring Ring

		// spnPriorityAddTask
		ArrayAdapter<CharSequence> spinnerAdapter0 = ArrayAdapter.createFromResource
			( this, R.array.activity_tasks_add_lstpriority, android.R.layout.simple_spinner_item);
		spinnerAdapter0.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnPriorityAddTask.setAdapter(spinnerAdapter0);
		
		// spnTypeAddTask
		ArrayAdapter<CharSequence> spinnerAdapter1 = ArrayAdapter.createFromResource
			( this, R.array.activity_tasks_add_lsttype, android.R.layout.simple_spinner_item);
		spinnerAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnTypeAddTask.setAdapter(spinnerAdapter1);
			
		//spnSoundAddTask
		ArrayAdapter<CharSequence> spinnerAdapter2 = ArrayAdapter.createFromResource
			( this, R.array.activity_tasks_add_lstsound, android.R.layout.simple_spinner_item);
		spinnerAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnSoundAddTask.setAdapter(spinnerAdapter2);
	}
	
	//--------- set spinner listener---------
	public void addSpinnerListener() {
		//spnPriorityAddTask
		spnPriorityAddTask.setOnItemSelectedListener( new OnItemSelectedListener()
		{	@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItem, int position, long id){ 
				switch (position){	
					case 0: //normal
						rtbarAddTask.setRating(1);	
					break;
					case 1: //important
						rtbarAddTask.setRating(2);	
					break;
					case 2: //very important
						rtbarAddTask.setRating(3);	
					break;			
		}
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0)
			{
			}
		});	
		//spnTypeAddTask
		spnTypeAddTask.setOnItemSelectedListener( new OnItemSelectedListener()
		{	@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItem, int position, long id){
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0){
			}
		});		
		//spnSoundAddTask
		spnSoundAddTask.setOnItemSelectedListener( new OnItemSelectedListener()
		{	@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItem, int position, long id){
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0){
			}
		});
	}
	
	
	//------ connect to change button, and time date EditText

	
	public void connectChangeButton()
	{	btnDateAddTask = (Button) findViewById(R.id.btnDateAddTask);
		btnTimeAddTask = (Button) findViewById( R.id.btnTimeAddTask);
		txtDateAddTask = (EditText) findViewById( R.id.txtDateAddTask);
		txtTimeAddTask = (EditText) findViewById( R.id.txtTimeAddTask);
		//set default current date time for EditText
		Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH)+1;
		day = c.get(Calendar.DAY_OF_MONTH);
		txtDateAddTask.setText(""+((day<10)? "0"+day : day)+"/"+((month<10)? "0"+month : month)+"/"+year);
		// for time
		hour = c.get( Calendar.HOUR);
		minute = c.get(  Calendar.MINUTE);
		ampm = c.get( Calendar.AM_PM);
		txtTimeAddTask.setText(""+((hour<10)? "0"+hour : hour)+":"+((minute<10)? "0"+minute : minute)+":"+ ((ampm==0)? "AM" : "PM"));	
		

		//add listener for button
		addListenerForDateTimeButton();
	}
	
	public void addListenerForDateTimeButton(){	
		btnDateAddTask.setOnClickListener( new OnClickListener()
		{	@SuppressWarnings("deprecation")
		@Override
			public void onClick(View v)
			{	showDialog(DIALOG_DATE);				
			}
		});
		btnTimeAddTask.setOnClickListener( new OnClickListener()
		{	@SuppressWarnings("deprecation")
		@Override
			public void onClick(View v)
			{	showDialog(DIALOG_TIME);				
			}
		});
	}
	
	// =============add listenner for change date time button==========
	@Override
	protected Dialog onCreateDialog(int id)
	{	switch (id)
		{	case DIALOG_DATE://click on date change button
				// set date picker as current date
				//return new DatePickerDialog(this, datePickerListener, year, month, day);
			/*chu y, vi cai acti nay trong group nen khong truyen this, ma truyen getparent()*/
				return new DatePickerDialog(getParent(), datePickerListener, year, month, day);
			case DIALOG_TIME://click on time change button
				// ampm = c.get... , ampm=0 ~~AM, =1 ~~PM
				return new TimePickerDialog(getParent(), timePickerListener, hour, minute, false);
		}
		return null;
	}
	/*o day viet lai mot OnDateSetListener de lam doi tuong 
	 * return ben trong ham onCreateDialog*/
	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener()
	{	public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
		{	// when user finish choose date, this command will be call
			day = selectedDay;
			month = selectedMonth+1;
			year = selectedYear;
			// reset date for EditText
			txtDateAddTask.setText(""+((day<10)? "0"+day : day)+"/"+((month<10)? "0"+month : month)+"/"+year);
		}
	};
	private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener()
	{	public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute)
		{	Log.i(" Hour = ", ""+selectedHour);
			minute = selectedMinute;
			if( selectedHour > 12)
			{	hour = selectedHour - 12;
				ampm = 1;
			}
			else
			{	hour = selectedHour;
				ampm = 0;
			}
			//reset time for EditText
			txtTimeAddTask.setText(""+((hour<10)? "0"+hour : hour)+":"+((minute<10)? "0"+minute : minute)+":"+ ((ampm==0)? "AM" : "PM"));	
		}	
	};
	
	//=======================//xu ly button OK and DELETE //====================
	private void AddListenerForOKDELETEButton() {
		// TODO Auto-generated method stub
		btnOKAddTask.setOnClickListener( new OnClickListener()
		{	

		public void onClick(View arg0)
			{	
				// get info
				Task item = new Task();
	
				item.setContent(txtContentAddTask.getText().toString());
				item.setType(spnTypeAddTask.getSelectedItem().toString().trim());
				item.setPriority(spnPriorityAddTask.getSelectedItemPosition()+1);
				item.setStatus(chkStatusAddTask.isChecked());
				item.setTime(txtTimeAddTask.getText().toString().trim());
				item.setDate(txtDateAddTask.getText().toString().trim());
				item.setSound(spnSoundAddTask.getSelectedItem().toString().trim());			
				//add a new task 
				if (selected_id==0) {
				// create task to insert to database

						
				//add to database
				TasksDAO.getInstance().addTasks(item);
				
				/*AlertDialog.Builder alertDialogBuilder  = new AlertDialog.Builder(context);
				alertDialogBuilder.setTitle("Message");
				alertDialogBuilder.setMessage("Finished adding a task");
				alertDialogBuilder.setPositiveButton("OK", null);
				alertDialogBuilder.setCancelable(true);
				alertDialogBuilder.create().show();*/
				Toast.makeText(getApplicationContext(), "Finished adding a task", Toast.LENGTH_LONG).show();
				} else {
				//update task
				item.setId(selected_id);
				//update to database
				TasksDAO.getInstance().updateTasks(item);
				finish();
				}
			}
		});
		btnDelAddTask.setOnClickListener( new OnClickListener()
		{	

		public void onClick(View arg0)
			{	
				if (selected_id==0) {
					//huy them moi >> thoat activity_task_add
				} else {
					//dele
					TasksDAO.getInstance().deleteTasksByID(selected_id);
				}
				finish();
			}
		});		
		
	}
		
	//======== get info from intent======
	public void getInfoFromIntent()
	{	Intent intent = getIntent();
		String AddOrEdit = intent.getStringExtra("AddOrEdit");
	
		if( AddOrEdit.equals("edit"))
		{	Bundle bundle = intent.getExtras();
			Task item = (Task)bundle.getSerializable("task");
				//set data for views
			txtContentAddTask.setText(item.getContent().trim());
			for (int i=0;i<spnTypeAddTask.getCount();i++)
			{
				if(spnTypeAddTask.getItemAtPosition(i).toString().trim().equals(item.getType().trim())) {		
					spnTypeAddTask.setSelection(i);
					break;
					}	
			}
			spnPriorityAddTask.setSelection(item.getPriority()-1);
			chkStatusAddTask.setChecked(item.getStatus());
			txtTimeAddTask.setText(item.getTime().trim());
			txtDateAddTask.setText(item.getDate().trim());
			for (int i=0;i<spnSoundAddTask.getCount();i++)
			{
				if(spnSoundAddTask.getItemAtPosition(i).toString().trim().equals(item.getSound().trim())) {
					spnSoundAddTask.setSelection(i);
					break;
					}
			}
			selected_id = item.getId();	
			btnDelAddTask.setText("Delete");
		}
	}
			

}
